package pl.lodz.p.mbus;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;



public class ContentFragment extends Fragment {

	
	
	private TextView currentTv;
	private TextView setTv;
	private int current;
	private int set;
	private int max = 290;
	private int min = 150;
	private Sensor s;


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 return inflater.inflate(R.layout.content_layout, container, false);

	}
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		currentTv = (TextView)getActivity().findViewById(R.id.TextTempCurrent);
		setTv = (TextView)getActivity().findViewById(R.id.textTempSet);
		Button b = (Button)getActivity().findViewById(R.id.applyButton);
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new ModbusWrite().execute(fromFloat(setTv.getText().toString()),Integer.valueOf(s.set));
				
			}
		});
		ImageButton increment = (ImageButton)getActivity().findViewById(R.id.increment);
		increment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				incrementSet(arg0);
			}
		});
		
		ImageButton decrement = (ImageButton)getActivity().findViewById(R.id.decrement);
		decrement.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
					decrementSet(arg0);
			}
		});		
	}
	
	public void updateContentView (Sensor s){
		this.s = s;
		new ModbusRead().execute(Integer.valueOf(s.current),Integer.valueOf(s.set),Integer.valueOf(s.max));
	}
	
	
	private class ModbusRead extends AsyncTask<Integer, Void, Object>{
		@Override
		protected Object doInBackground(Integer... register) {
	        ModbusMaster master = ((MbusApplication) (getActivity().getApplicationContext() )).getMaster();
	        Object[] vals = new Object[3];
	        try {
                vals[0] = master.getValue(2, RegisterRange.HOLDING_REGISTER, register[0],
	                        DataType.TWO_BYTE_INT_UNSIGNED) ;
              vals[1]= master.getValue(2, RegisterRange.HOLDING_REGISTER, register[1],
                        DataType.TWO_BYTE_INT_UNSIGNED) ;
                vals[2] = master.getValue(2, RegisterRange.HOLDING_REGISTER, register[2],
                        DataType.TWO_BYTE_INT_UNSIGNED);
                
	        }
	        catch (Exception e){
	        	e.printStackTrace();
	        	vals[0]=vals[1]=vals[2]=Integer.valueOf(-10);
	        }
	        return vals;
		}
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			currentTv.setText (  toFloat(( ((Object[])result)[0] ).toString())  );
			setTv.setText ( toFloat( ( ((Object[])result)[1] ).toString() ) );
			max = Integer.valueOf( ( ((Object[])result)[2] ).toString() );
		}
	}
	
	private class ModbusWrite extends AsyncTask<Integer, Void, Object>{
		@Override
		protected Object doInBackground(Integer... register) {
	        ModbusMaster master = ((MbusApplication) (getActivity().getApplicationContext() )).getMaster();
	        try {
	           master.setValue(2, RegisterRange.HOLDING_REGISTER, register[1], DataType.TWO_BYTE_INT_UNSIGNED, register[0]);
                
	        }
	        catch (Exception e){
	        	e.printStackTrace();
	        }
	        return null;
		}
	}
	
	private String toFloat (String value){
		return new StringBuilder(value).insert(value.length()-1,".").toString();
	}
	
	private Integer fromFloat (String value){
		return Integer.valueOf(value.replace(".", ""));
	}
	
	
	public void decrementSet (View v){
		Integer value = fromFloat(setTv.getText().toString());
		value-=5;
		if (value < min){
			Toast.makeText(getActivity().getApplicationContext(), "Temperatura minimalna", Toast.LENGTH_SHORT).show();
			return;
		}
		setTv.setText(toFloat(value.toString()));
	}
	
	public void incrementSet (View v){
		Integer value = fromFloat(setTv.getText().toString());
		value+=5;
		if (value > max){
			Toast.makeText(getActivity().getApplicationContext(), "Temperatura maksymalna", Toast.LENGTH_SHORT).show();
			return;
		}
		setTv.setText(toFloat(value.toString()));
	}

}
